﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Models;
using App.Views.ViewModels;
using App.Models.Pager;

namespace App.Controllers
{
    public class WakeServiceController : BaseController
    {
        public ActionResult Index()
        {            
            return View();
        }
         public ActionResult List(int? page, int? rows, string order)
        {
            dbe.ContextOptions.ProxyCreationEnabled = false;
            dbe.ContextOptions.LazyLoadingEnabled = false;

            int offset = (page ?? 1 - 1) * (rows ?? 10);            
            PagedList<tb_WakeRecords> list = null;
            if ("asc" == order)
            {
                list = dbe.tb_WakeRecords.OrderBy(m => m.WakeNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }else{
                list = dbe.tb_WakeRecords.OrderByDescending(m => m.WakeNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            PagedList<WakeServiceEditViewModel> data = new PagedList<WakeServiceEditViewModel>(
                                                list.CurrentPageIndex,list.PageSize,list.total);
            data.rows.AddRange(from f in list.rows
                          select new WakeServiceEditViewModel
                          {
                              WakeNO = f.WakeNO,
                              ServiceNo = f.ServiceNo,
                              DeadNO = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == f.ServiceNo).DeadNO,
                              HallNO = f.HallNO,
                              StartTime = f.StartTime,
                              EndTime = f.EndTime
                          });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

         public ActionResult Create()
         {
             var vmodel = GetServiceItemList("", Utils.WAKE_SERVICE_TYPE);
             return PartialView("UCServicesItemList", vmodel);
         }
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try {
                //费用明细选择，通过页面的JS生成发下格式： id,qty,subtotal|id,qty,..
                //保存在SelectedItemList属性中
                string serviceNo = GenServiceNo();
                AddServiceItems(collection["DeadNO"], serviceNo, collection["SelectedItemList"]);
                DateTime st = DateTime.Parse(collection["StartTime"]);
                DateTime et = DateTime.Parse(collection["EndTime"]);
                var model = new tb_WakeRecords
                {
                    WakeNO = GenWakeNO(),
                    ServiceNo = serviceNo,
                    HallNO = collection["HallNO"],
                    StartTime = st,
                    EndTime = et
                };

                dbe.tb_WakeRecords.AddObject(model);
                dbe.SaveChanges();
                CurrentDeader = collection["HallNO"];
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch{
                return Json(new { success = false, msg = "添加出错！" }, JsonRequestBehavior.AllowGet);
            }
            
        }

        public ActionResult Edit(string id)
        {
            var model = dbe.tb_WakeRecords.FirstOrDefault(m => m.WakeNO == id);
            var vmodel = GetServiceItemList(model.ServiceNo, Utils.WAKE_SERVICE_TYPE);
            return PartialView("UCServicesItemList", vmodel);
        }
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            try
            {
                string serviceNo = collection["ServiceNo"];
                var serviceDetail = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == serviceNo);
                var model = dbe.tb_WakeRecords.FirstOrDefault(m => m.WakeNO == id);
                model.HallNO = collection["HallNO"];
                model.StartTime = DateTime.Parse(collection["StartTime"]);
                model.EndTime = DateTime.Parse(collection["EndTime"]);

                //更新服务收费
                EditServiceItems(collection["SelectedItemList"], collection["DeadNO"], collection["ServiceNo"]);

                dbe.SaveChanges();
                CurrentDeader = collection["DeadNO"];
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "保存出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            
        }
        
        [HttpPost]
        public ActionResult Delete(string ids)
        {
            try
            {
                string[] idList = ids.Split('&');
                foreach (var id in idList)
                {
                    var obj = dbe.tb_WakeRecords.FirstOrDefault(m => m.WakeNO == id);
                    dbe.tb_WakeRecords.DeleteObject(obj);
                    //删除服务收费
                    DeleteServiceItems(obj.ServiceNo);
                }

                dbe.SaveChanges();
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "删除出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult SelectWakeHall(string st, string et) {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));

            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;
            try
            {
                stime = DateTime.Parse(st);
                etime = DateTime.Parse(et);
                if (stime.CompareTo(DateTime.MinValue)<=0) stime = DateTime.Now;
                if (stime.CompareTo(DateTime.MinValue)<=0) etime = stime;

            }
            catch
            {

            }
            var list = dbe.tb_WakeHallInfo.ToList();
            //统计在StartTime - EndTime 这个段时间已经预约或在用房间
            var useds = dbe.tb_WakeRecords.Where(m => m.StartTime <= etime && m.EndTime > stime);
            var usedIdList = useds.Select(m => m.HallNO).ToList();
            var usedList = useds.ToList();
            var lv = new List<WakeHallStatusViewModel>();
            foreach (var c in list)
            {
                string status = "空闲";                
                string hintMsg = "";
                int pos = usedIdList.IndexOf(c.HallNO);
                if (pos >= 0)
                {
                    status = "在用";
                    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].StartTime, usedList[pos].EndTime);
                }
                var lvi = new WakeHallStatusViewModel
                {
                    HallNO = c.HallNO,
                    HallName = c.HallName,
                    Status = status,
                    Remark = hintMsg
                };
                lv.Add(lvi);
            }     
            return PartialView(lv);
        }
    }
}
